<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/04
 * Time: 17:14
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\cha;

use app\admin\controller\BaseController;
use app\common\model\Channel;
use app\common\model\ChannelCarrier;
use app\common\model\SysCountries;
use app\common\service\logistics\ChannelService;
use think\facade\Validate;

/**
 * 渠道管理
 * Class IndexController
 * @package app\admin\controller\channel
 */
class ChannelController extends BaseController
{
    /**
     * 渠道列表
     * @date 2020/09/18
     * @author longli
     */
    public function index()
    {
        if(!$this->request->isAjax()) return $this->fetch('index');
        $this->assign('list', Channel::with(['carrier'])->order("sort desc,carrier_id")->select());
        return $this->fetch('lists');
    }

    /**
     * 更新渠道
     * @date 2020/09/18
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $data = $this->request->post();
            // 普通验证
            $validate = Validate::make([
                'carrier_id'  => 'require',
                'channel_name'  => 'require',
                'channel_type'  => 'require',
                'day_max_qty'  => 'egt:0',
                'default_weight'  => 'egt:0',
                'default_discount'  => 'integer|between:0,101',
                'label_width'  => 'egt:0',
                'label_height'  => 'egt:0',
            ],[
                'carrier_id.require'      => '渠道必选',
                'channel_name.require'    => '渠道名称必填',
                'channel_type.require'    => '渠道类型必选',
                'day_max_qty.egt'         => '单日发货量有误',
                'default_weight.egt'      => '起重有误',
                'default_discount.integer'=> '折扣只能是整数',
                'default_discount.between'=> '折扣只能是1-100的整数',
                'label_width.egt'         => '面单宽度有误',
                'label_height.egt'        => '面单高度有误',
            ]);
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
            if(empty($data['label_width'])) $data['label_width'] = 100;
            if(empty($data['label_height'])) $data['label_height'] = 100;
            if(!isset($data['status'])) $data['status'] = Channel::STATUS_N;
        }
        else
        {
            $validate = Validate::make([
                'channel_id'  => 'require',
            ],[
                'channel_id.require' => '非法请求',
            ]);
            $data = $this->request->only(['channel_id', 'status'], 'get');
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        }
        ChannelService::getInstance()->addChannel($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 录入渠道
     * @date 2020/09/18
     * @author longli
     */
    public function add()
    {
        $this->assign("channel_type", Channel::$CHANNEL_TYPE);
        $this->assign("carrier", ChannelCarrier::getAll());
        $this->assign("is_track", Channel::$IS_TRACK);
        $this->assign("track_type", Channel::$TRACK_TYPE);
        $this->assign("label_type", Channel::$LABEL_TYPE);
        $this->assign("billing_type", Channel::$BILLING_TYPE);
        $channelId = $this->request->request("channel_id");
        if(!empty($channelId)) $this->assign("channel", Channel::get($channelId));
        return $this->fetch("add");
    }

    /**
     * 删除渠道
     * @date 2020/09/18
     * @author longli
     */
    public function delete()
    {
        $channelId = $this->request->request("ids");
        if(empty($channelId)) $this->error('参数错误');
        Channel::destroy($channelId);
        $this->success('删除成功');
    }

    /**
     * 试算运费
     * @date 2021/09/02
     * @author longli
     */
    public function calculate()
    {
        if(!$this->request->isPost())
        {
            $this->assign('counties', SysCountries::getCodeNameCh());
            return $this->fetch('calculate');
        }
        $service = \app\common\service\logistics\ChannelOrderService::getInstance();
        $type = $this->request->request('type', 'order', 'trim');
        $list = [];
        if($type == 'weight')
        {
            $weight = $this->request->post('weight', '0', 'trim');
            $code = $this->request->post('country_code');
            if(empty($code)) $this->error("国家必选");
            if(!is_numeric($weight)) $this->error("请输入正确的重量");
            try
            {
                $list = $service->calculateByWeight($code, $weight);
            }catch(\Exception $e)
            {
                $this->error("数据异常");
            }
        }
        else if($type == 'order')
        {
            // 通过订单试算
            $orderSn = $this->request->post('order_sn', '', 'trim');
            if(empty($orderSn)) $this->error("订单号不能为空");
            $order = \app\common\model\Orders::getSnNo($orderSn);
            if(empty($order)) $this->error("订单不存在");
            try
            {
                $list = $service->calculateByOrder($order);
            }catch(\Exception $e)
            {
                $this->error("数据异常");
            }
        }
        else if($type == 'sku')
        {
            // 通过商品试算
            $skus = $this->request->post('sku');
            $skus = explode(',', $skus);
            $qtys = $this->request->post('qty');
            $code = $this->request->post('country_code');
            if(empty($code)) $this->error("国家必选");
            $data = [];
            foreach($qtys as $k => $qty)
            {
                if(empty($qty) || $qty < 0) $this->error("数量【{$qty}】错误");
                if(empty($skus[$k])) $this->error("SKU必选");
                $data[] = [
                    "sku" => $skus[$k],
                    "qty" => $qty,
                ];
            }
            try
            {
                $list = $service->calculate($code, $data);
            }catch(\Exception $e)
            {
                $this->error("数据异常");
            }
        }
        $this->assign('list', $list);
        return $this->fetch("calculate_list");
    }

    /**
     * 获取渠道列表
     * @date 2020/09/18
     * @author longli
     */
    public function channel_list()
    {
        $channel = Channel::field(["channel_id", "channel_code", "channel_name"])
                    ->order("sort desc, carrier_id");
        $this->searchModel($channel, [
            'in' => ['carrier_id'],
            'like' => ['channel_code', 'channel_name'],
        ]);
        $this->success('获取成功', '', $channel->select());
    }
}